<?php
require_once('db_config.inc.php');
require_once('config.inc.php');
require_once(LIB_DIR.'search.php');
require_once(LIB_DIR.'DB.php');
require_once(LIB_DIR.'Pager.php');
require_once(LIB_DIR.'functions.php');

header("Content-type: text/html; charset=utf-8");

$keyword = "";
if( isset($_GET['q'])){
	$keyword = $_GET['q'];

	$sortby = "";
	if( isset($_GET['sortby']) ){
		$sortby = htmlspecialchars($_GET['sortby']);
	}
	$page = 1;
	if( isset($_GET['p']) ){
		$page = intval($_GET['p']);
	}

	$searchObj = new Search();
	//clean keyword
	$keyword = $searchObj->CleanKeyword( $keyword );

	$searchType = NORMAL_QUERY;

	if( !empty( $sortby ) ) {
		$sortbyArray = explode( "-", $sortby );
		if( count($sortbyArray) == 2 ){
			$sortby = $sortbyArray[0];
			$isDesc = $sortbyArray[1] == "asc"? false : true;
		}
		else {
			$sortby = "";
		}

		if( $sortby != "" ){
			if( $searchType == FILTER_QUERY ) {
				$searchType = FILTER_SORT_QUERY;
			}
			else {
				$searchType = SORT_QUERY;
			}
		}
	}

	switch( $searchType ) {
		case NORMAL_QUERY:
			$result = $searchObj->Query( $keyword, $page );
			break;
		case SORT_QUERY:
			$result = $searchObj->SortQuery( $keyword, $sortby, $page, $isDesc );
			break;
		case FILTER_QUERY:
			$result = $searchObj->MultiFilterQuery( $keyword, $filterArray, $page );
			break;
		case FILTER_SORT_QUERY:
			$result = $searchObj->MultiFilterAndSortQuery( $keyword, $filterArray, $sortby, $page, $isDesc );
			break;
		case RANGE_FILTER_SORT_QUERY:
			$result = $searchObj->MultiRangeFilterAndSortQuery( $keyword, $filterArray, $sortby, $page, $isDesc );
			break;
	}

	if( $result['total'] > 0 ) {
		$db = new DB();
		$strIds = implode( ",", $result['matchIds'] ); 
		$sql = "select * from spider_content where id in (".$strIds.") ORDER BY FIELD(id, ".$strIds.")";
		$rows = $db->GetPlan( $sql );

		$rowsHighlight = array();
		foreach( $rows as $row ) {
			$arrToHighlight = array
			(
					'title' => $row['title'],
					'content' => $row['content'],
					'author' => $row['author'],
					'abstract' => $row['abstract']
			);
			$row = array_merge( $row, $searchObj->BuildHighLight( $keyword, $arrToHighlight ) );
			//and set location and shopname

			$rowsHighlight[] = $row;
		}

		//pager info
		$pageObj = new Pager("index.php?q=".urlencode($keyword)."&sortby=$sortby&p=$page",
			$result['total'], 20, $page, "p" );

		$TPL->assign( "searchresult", $result );
		$TPL->assign( "pagebar", $pageObj->getBar() );
		$TPL->assign( "rows", $rowsHighlight );
		$TPL->assign( "keyword", $keyword );

		$allTemplates = GetAllWebSiteInfo();
		$TPL->assign( "alltemplates", $allTemplates );
		
		//unload db vars
		Unload();
	}
}
else{
}

$TPL->display( "index2.tpl" );
?>
